/*
 * ErrorCode.h
 *
 *  Created on: Aug 2, 2016
 *      Author: Lucifer
 */

#ifndef BFX_SOCKETERROR_H_
#define BFX_SOCKETERROR_H_

#include <errno.h>

namespace BFX {


class SocketError {
public:
	/// Predefined errors.
	enum {
		EC_Success = 0,	/// The operation completed successfully.
		EC_IllegalStateError = -1,	/// The socket has an error.
		EC_Interrupted = EINTR,	///  A blocking socket call was canceled.
		EC_BadFileDescriptor = EBADF,	/// Invalid file descriptor.
		EC_AccessDenied = EACCES,	/// Permission denied.
		EC_InvalidArgument = EINVAL,	/// Invalid argument.
		EC_TooManyOpenFiles = ENFILE,	/// Too many open files.
		EC_NoBufferSpaceAvailable = ENOBUFS,	/// No buffer space available.
		EC_AddressFamilyNotSupported = EAFNOSUPPORT,/// Address family not supported by protocol family.
		EC_ProtocolFamilyNotSupported = EPROTONOSUPPORT,	/// Unknown protocol.
		// XXX More error definitions
	};

public:
	/**
	 * Gets the current thread's last error code. The last error code is maintained on a per-thread
	 * basis. Threads will not overwrite each other's last error code.
	 * @return
	 */
	static int get();
	/**
	 * Sets the last error code for the current thread.
	 * @param ec
	 */
	static void set(int ec);

	/**
	 * Clears the last error (EC_Success) for the current thread.
	 */
	static void clear();

	/**
	 * Sets last error code from OS (errno or GetLastError).
	 * @return
	 */
	static void updateSysError();
	/**
	 * Updates last error code by given condition.
	 * @param hasError Set from OS error code if true; otherwise set to EC_Success.
	 */
	static void update(bool hasError);

	/**
	 * Gets the message string for specified error code.
	 * @param ec
	 * @return
	 */
	static const char* getErrorMessage(int ec);

private:
	// Avoid instantiation.
	SocketError();
};


} /* namespace BFX */

#endif /* BFX_SOCKETERROR_H_ */
